package com.drondea.testclient.service;

import com.drondea.sms.channel.ChannelSession;
import com.drondea.sms.message.IMessage;
import com.drondea.sms.message.sgip12.SgipSubmitRequestMessage;
import com.drondea.sms.thirdparty.SmsAlphabet;
import com.drondea.sms.thirdparty.SmsDcs;
import com.drondea.sms.type.IMessageResponseHandler;
import com.drondea.testclient.panel.SgipPanel;
import com.drondea.testclient.service.provider.SgipClientMessageProvider;
import com.drondea.testclient.util.CommonThreadPoolFactory;
import com.drondea.testclient.util.counter.SgipAtomicUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 发送服务类 2
 *
 * @author sun
 * 2019年4月23日 下午2:25:34
 */

@Slf4j
public class SgipService extends AbstractTcpService {

    private static final SgipPanel PANEL = SgipPanel.getInstance();
    private static final SgipService INSTANCE = new SgipService();

    private SgipService() {}
    public static SgipService getInstance() {
        return INSTANCE;
    }

    @Override
    public void sendSms(String mobile, String content, String subCode) {
        try {
            SgipSubmitRequestMessage requestMessage = new SgipSubmitRequestMessage();
            requestMessage.setMsgContent(content);
            requestMessage.setServiceType("5");
            requestMessage.setSpNumber(subCode);
            requestMessage.setCorpId("AAAA");
            requestMessage.setReportFlag((short) 1);
            requestMessage.setUserCount((short) 1);
            requestMessage.setUserNumber(new String[]{mobile});
            requestMessage.setMessageCoding(SmsDcs.getGeneralDataCodingDcs(SmsAlphabet.RESERVED));
            requestMessage.setMessageResponseHandler(new IMessageResponseHandler() {

                @Override
                public void messageComplete(IMessage requestMsg, IMessage responseMsg) {
                    log.debug("messageComplete");
                    SgipAtomicUtil.handlerDelay(System.currentTimeMillis() - requestMsg.getSendTimeStamp());
                }

                @Override
                public void messageExpired(String s, IMessage iMessage) {
                    log.error("messageExpired");
                    SgipAtomicUtil.handlerDelay(System.currentTimeMillis() - iMessage.getSendTimeStamp());
                }

                @Override
                public void sendMessageFailed(IMessage iMessage) {
                    SgipAtomicUtil.handlerDelay(System.currentTimeMillis() - iMessage.getSendTimeStamp());
                    log.error("sendMessageFailed");
                }
            });
            log.debug("SgipSubmitRequestMessage = {}", requestMessage);
            sendMessage(requestMessage);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    private void sendMessage(SgipSubmitRequestMessage requestMessage) {
        List<ChannelSession> sessions = PANEL.sessionManager.getSessions();
        if (sessions == null || sessions.size() == 0) {
            log.error("ChannelSession为空，无法发送短信，等待稍后重试。。。");
            PANEL.sessionManager.doOpen();
            resendMessageDelay(requestMessage, 500);
            return;
        }
        SgipClientMessageProvider messageProvider = (SgipClientMessageProvider) PANEL.sessionManager.getMessageProvider();
        boolean hasSend = messageProvider.addMessage(requestMessage);
        if (!hasSend) {
            resendMessageDelay(requestMessage, 1000);
        }
    }

    public void resendMessageDelay(SgipSubmitRequestMessage requestMessage, int delay) {
        CommonThreadPoolFactory.getInstance().getScheduleExecutor().schedule(() -> 
                sendMessage(requestMessage), delay, TimeUnit.MILLISECONDS);
    }

}
